import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:people_big_people/bean/resp/base_resp.dart';
import 'package:people_big_people/utils/log_util.dart';
import '../builder/BaseBean.dart';
import '../builder/BeanTrans.dart';
import '../utils/sp_util.dart';

///获取请求单例
var dioManager = DioManager.instance;

class DioManager {
  factory DioManager() => _getInstance();

  static DioManager get instance => _getInstance();
  static DioManager? _instance;

  ///初始化方法
  DioManager._internal();

  static DioManager _getInstance() {
    return _instance ??= DioManager._internal();
  }

  final isPrd = false;

  final PRD_HOST = "";
  final DEV_HOST = "";

  ///get请求
  void getHttp(String url) async {
    try {
      Response response = await Dio().get(url);
      LogUtil.i(response);
    } catch (e) {
      LogUtil.i(e);
    }
  }

  ///post 请求数据
  Future<T> postHttp<T extends BaseResp>(String url, BaseBean baseBean) async {
    T t = generateBeanObject2();
    dynamic error;
    try {
      Response response = await Dio().request("$PRD_HOST$url", data: baseBean.toJson(), options: mOptions());
      LogUtil.i("接口 ${url.split("/").last} 请求信息  ：${response.requestOptions.data}");
      LogUtil.i("接口 ${url.split("/").last} 返回信息  ：$response");
      t.loadJsonString(jsonEncode(response));
    } catch (e) {
      LogUtil.i("接口 ${url.split("/").last} 错误信息  ：${e.toString()}");
      error = e;
    }
    return t;
  }

  ///请求设置
  Options mOptions() {
    Options options = Options();
    String token = SpUtils.getToken();
    if (token.isNotEmpty) options.headers = {"token": token};
    options
      ..method = 'POST'
      ..sendTimeout = 5000
      ..receiveTimeout = 3000
      ..contentType = "application/x-www-form-urlencoded";
    return options;
  }

  ///创建拦截器
  void mInterceptor() {}
}
